package com.lc.activiti.config;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lc.activiti.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 自动填充器
 * @author: 骆超
 * @date: 2021/5/21 9:41
 */
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Resource
    private HttpServletRequest request;
    @Resource
    private HttpServletResponse response;

    /**
     * 新增时的默认值设置
     * @author 骆超
     * @date 2021/5/21
     * @param metaObject 参数说明
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        String token = request.getHeader("token");
        if (StringUtils.isNotEmpty(token)&&!"null".equals(token)){
            Long id = (Long) JwtUtil.getObjectByKey(token,"id");
            this.setFieldValByName("createUser", id,metaObject);
        }
        Date now = DateUtil.date();
        this.setFieldValByName("updateDate",now ,metaObject);
        this.setFieldValByName("createDate", now,metaObject);
    }

    /**
     * 修改时的默认值设置
     * @author 骆超
     * @date 2021/5/21
     * @param metaObject 参数说明
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateDate", DateUtil.date(),metaObject);
        String token = request.getHeader("token");
        if (StringUtils.isNotEmpty(token)&&!"null".equals(token)){
            Long id = (Long) JwtUtil.getObjectByKey(token,"id");
            this.setFieldValByName("updateUser", id,metaObject);
        }
    }
}
